import { defineAsyncComponent, ref, computed, watch } from 'vue';
import { ElDialog, ElButton, ElMessage } from 'element-plus';
import type { PropType } from 'vue';
import type { SftpFileContentDTO } from '@/types';

export default {
  name: 'SftpEditModal',
  components: {
    ElDialog,
    ElButton,
    // 使用 defineAsyncComponent 异步加载 Monaco Editor 以减少初始包大小
    MonacoEditor: defineAsyncComponent(() => import('@guolao/vue-monaco-editor').then((mod) => mod.default))
  },
  props: {
    modelValue: {
      type: Boolean as PropType<boolean>,
      required: true
    },
    filePath: {
      type: String as PropType<string>,
      required: true
    },
    connectionId: {
      type: String as PropType<string>,
      required: true
    },
    initialContent: {
      type: String as PropType<string>,
      required: true
    },
    lastModified: {
      type: Number as PropType<number>,
      required: true
    }
  },
  emits: ['update:modelValue', 'success'],
  setup(props: any, { emit }: any) {
    const editorContent = ref(props.initialContent);
    const isSaving = ref(false);

    const visible = computed({
      get: () => props.modelValue,
      set: (value: boolean) => emit('update:modelValue', value)
    });

    watch(() => props.initialContent, (newVal: string) => {
      editorContent.value = newVal;
    });

    const handleEditorChange = (value: string | undefined) => {
      editorContent.value = value || '';
    };

    const handleClose = (done: () => void) => {
      done();
    };

    const handleSave = async () => {
      if (isSaving.value) return;
      isSaving.value = true;

      try {
        const sftpApi = (await import('@/api/sftp')).default;
        const params = {
          id: props.connectionId,
          path: props.filePath,
          content: editorContent.value,
          lastModified: props.lastModified
        };

        const res = await sftpApi.saveFileContent(params);
        if (res.code === 'Success') {
          ElMessage.success(res.message || '保存成功');
          emit('success');
          visible.value = false;
        } else {
          if (res.message?.includes('文件在您编辑期间已被其他用户修改')) {
             ElMessage.error(res.message);
          } else {
             ElMessage.error(res.message || '保存失败');
          }
        }
      } catch (error: any) {
        console.error('保存文件时发生错误:', error);
        ElMessage.error(error.message || '保存失败');
      } finally {
        isSaving.value = false;
      }
    };

    return {
      editorContent,
      isSaving,
      visible,
      handleEditorChange,
      handleClose,
      handleSave
    };
  }
};